const request = require('request');

// 获取 code
function getCode() {
  const options = {
    uri: 'https://cloud.minapp.com/api/oauth2/hydrogen/openapi/authorize/',
    method: 'POST',
    json: {
      client_id: 'ab9f4c1a9bb883d6fa47',
      client_secret: '4afc329b29a44aa7d204a5bf1d100bd142a4969b' // 请替换为你的 client_secret
    },
    jar: true,                // 允许记住 cookie 
    followAllRedirects: true, // 允许重定向
  };

  request(options, (err, res, body) => {
    if (err) {
      console.error('Error getting code:', err);
      return;
    }
    // 检查响应体中是否包含 code
    if (body && body.code) {
      getToken(body.code);  // 回调调用 getToken 函数
    } else {
      console.error('Failed to retrieve code:', body);
    }
  });
}

// 获取 access token
function getToken(code) {
  const options = {
    uri: 'https://cloud.minapp.com/api/oauth2/access_token/',
    method: 'POST',
    json: {
      client_id: 'ab9f4c1a9bb883d6fa47',
      client_secret: '4afc329b29a44aa7d204a5bf1d100bd142a4969b', // 请替换为你的 client_secret
      grant_type: 'authorization_code',
      code,
    }
  };

  request(options, (err, res, body) => {
    if (err) {
      console.error('Error getting access token:', err);
      return;
    }
    // 打印 access token
    console.log('Access Token:', body.access_token);
    console.log('Token Type:', body.token_type);
    console.log('Expires In:', body.expires_in);
    console.log('Refresh Token:', body.refresh_token);
    console.log('Scope:', body.scope);
  });
}

// 开始获取流程
getCode();
